"""版本操作"""

import os
import json
import zipfile

# 导入配置
from core import settings
from core import paths
from core import download
from core import checkhash
from core import tasks
from core import tools
from core import logs


def get_version_list(): # 获取所有版本
    path_list=paths.get_path_list()
    all_version=[]
    for this_name, this_path in path_list.items(): # 遍历所有路径
        tpath_vlist=os.listdir(this_path["path"] + "version/") # 读取所有版本
        for this_version in tpath_vlist: # 遍历当前路径下的版本
            all_version.append(
                {
                    "name": this_version, 
                    "path": this_path + this_version
                }
            )
    return all_version

def download_version(path,name,version,other): # 安装一个版本
    def subtask(tool,path,name,version,other):
        tool.set_status("下载版本描述文件 (1/"+str(len(other)+4)+")")
        tool.set_progress(0)
        if not os.path.exists(path+"version"+"/"+name+"/"):
            os.makedirs(path+"version"+"/"+name+"/") # 创建目录
        game_path=path+"version"+"/"+name+"/"
        tool.set_progress(10)
        d_json=download.download_json(game_path, version)
        tool.set_progress(50)
        if not os.path.exists(path+"assets/indexes/"):
            os.makedirs(path+"assets/indexes/")
        if not os.path.exists(path+"assets/objects/"):
            os.makedirs(path+"assets/objects/")
        d_assjson=download.download_ass_index(path, game_path,version)
        tool.set_progress(100)
        tool.set_status("下载依赖 (2/"+str(len(other)+4)+")")
        tool.set_progress(0)
        libindex=json.loads(d_json)
        download.download_lib_file(path, tool, libindex)
        tool.set_progress(100)
        tool.set_status("下载主文件 (3/"+str(len(other)+4)+")")
        tool.set_progress(0)
        download.download_main_jar(path, tool, name, version)
        tool.set_progress(100)
        tool.set_status("下载资源文件 (4/"+str(len(other)+4)+")")
        assindex=json.loads(d_assjson) # dict
        download.download_ass_file(path, tool, assindex)
        tool.set_progress(100)
    tasks.add_task("下载版本 ["+version+"]", subtask, "准备中", -1, (path,name,version,other))

def unzip_natives(path,ver_json):
    lib_path=path+"libraries/"
    natives_path=settings.DATA_NATIVES_DIR+"natives-"+settings.PC_OS+"-"+settings.ARCH+"/"
    if not os.path.exists(natives_path):
        os.makedirs(natives_path)
    for info in ver_json["libraries"]:
        if "classifiers" in info["downloads"]:
            if ("natives-"+settings.PC_OS) in info["downloads"]["classifiers"]:
                this_path=lib_path+info["downloads"]["classifiers"][("natives-"+settings.PC_OS)]["path"]
                zip = zipfile.ZipFile(this_path)
                zip.extractall(natives_path)
                zip.close()
            if ("natives-"+settings.PC_OS+"-"+settings.ARCH) in info["downloads"]["classifiers"]:
                this_path=lib_path+info["downloads"]["classifiers"][("natives-"+settings.PC_OS+"-"+settings.ARCH)]["path"]
                zip = zipfile.ZipFile(this_path)
                zip.extractall(natives_path)
                zip.close()
def get_version_cmd(path,this_java,name,version,select_user,other_game="",other_jvm="",size=None):
    with open(path+"version"+"/"+name+"/"+version+".json") as file:
        get_json=json.loads(file.read())
    
    # 处理参数
    all_game_arg=""
    all_jvm_arg=""
    if "arguments" in get_json: # 新版处理
        if "game" in get_json["arguments"]:
            
            for this_arg in get_json["arguments"]["game"]:
                if type(this_arg) == str:
                    all_game_arg = all_game_arg + this_arg + " "
                elif type(this_arg) == dict:
                    if ("features" in this_arg["rules"][0]) and ("is_demo_user" in this_arg["rules"][0]["features"]):
                        if select_user["type"]=="offline" and not("jump_demo" in select_user):
                            all_game_arg = all_game_arg + this_arg["value"] + " "
                    if ("features" in this_arg["rules"][0]) and ("has_custom_resolution" in this_arg["rules"][0]["features"]):
                        if size != None: 
                            for this_size_args in this_arg["value"]:
                                all_game_arg = all_game_arg + this_size_args + " "
                    if ("os" in this_arg["rules"][0]) and ("name" in this_arg["rules"][0]["os"]) and (this_arg["rules"][0]["os"]["name"]==settings.PC_OS):
                        
                        if type(this_arg["value"])==str:
                            all_game_arg = all_game_arg + this_arg["value"] + " "
                        else:
                            for this_os_args in this_arg["value"]:
                                all_game_arg = all_game_arg + this_os_args + " "
        if "jvm" in get_json["arguments"]:
            for this_arg in get_json["arguments"]["jvm"]:
                if type(this_arg) == str:
                    all_jvm_arg = all_jvm_arg + this_arg + " "
                elif type(this_arg) == dict:
                    if ("features" in this_arg["rules"][0]) and ("is_demo_user" in this_arg["rules"][0]["features"]):
                        if select_user["type"] == "offline" and ("jump_demo" not in select_user):
                            all_jvm_arg = all_jvm_arg + \
                                this_arg["value"] + " "
                    elif ("features" in this_arg["rules"][0]) and ("has_custom_resolution" in this_arg["rules"][0]["features"]):
                        if size != None:
                            for this_size_args in this_arg["value"]:
                                all_jvm_arg = all_jvm_arg + this_size_args + " "
                    elif ("os" in this_arg["rules"][0]) and ("name" in this_arg["rules"][0]["os"]) and (str(this_arg["rules"][0]["os"]["name"]) == settings.PC_OS):
                        
                        if type(this_arg["value"]) == str:
                            all_jvm_arg = all_jvm_arg + \
                                this_arg["value"] + " "
                        else:
                            for this_os_args in this_arg["value"]:
                                all_jvm_arg = all_jvm_arg + this_os_args + " "
    elif "minecraftArguments" in get_json: # 旧版处理
        all_game_arg = get_json["minecraftArguments"] + " "
        for this_arg in settings.DEFAULT_JVM_AUGUMENT:
            if type(this_arg) == str:
                all_jvm_arg = all_jvm_arg + this_arg + " "
            elif type(this_arg) == dict:
                if ("features" in this_arg["rules"]) and ("is_demo_user" in this_arg["rules"]["features"]):
                    if select_user["type"] == "offline" and not ("jump_demo" in select_user):
                        all_jvm_arg = all_jvm_arg + \
                            this_arg["rules"]["value"] + " "
                if ("features" in this_arg["rules"]) and ("has_custom_resolution" in this_arg["rules"]["features"]):
                    if size != None:
                        for this_size_args in this_arg["rules"]["value"]:
                            all_jvm_arg = all_jvm_arg + this_size_args + " "
                if ("os" in this_arg["rules"]) and this_arg["rules"]["os"]["name"] == settings.PC_OS:
                    if type(this_arg["rules"]["value"]) == str:
                        all_jvm_arg = all_jvm_arg + \
                            this_arg["rules"]["value"] + " "
                    else:
                        for this_os_args in this_arg["rules"]["value"]:
                            all_jvm_arg = all_jvm_arg + this_os_args + " "
    all_plugin_game_arg=""
    all_plugin_jvm_arg=""
    main_class=get_json["mainClass"]
    all_cmd=this_java+" "+all_jvm_arg+all_plugin_jvm_arg+other_jvm+main_class+" "+all_game_arg+all_plugin_game_arg+other_game
    
    login_type=""
    if(select_user["type"]=="microsoft"): login_type=""
    else: login_type=="legacy"
    rep_uuid = select_user["uuid"].replace("-","")
    
    allcp=""
    for this_lib in get_json["libraries"]:
        allcp=allcp+(path+"libraries/"+this_lib["downloads"]["artifact"]["path"])+":"
    logs.log("INFO","start unzip natives","VERSIONS")
    unzip_natives(path, get_json)

    all_cmd=tools.render_arg(all_cmd,
            version_type=get_json["type"],
            launcher_name="ckLauncher",
            launcher_version=settings.VERSION,
            user_type=login_type,
            assets_root='"'+path+"assets/"+'"',
            game_directory='"'+path+"version/"+name+"/"+'"',
            version_name=version,
            assets_index_name=version,
            auth_uuid=rep_uuid,
            auth_xuid="86164787dc9e94701f1e36c2b522b2bc", # 随便生成的
            classpath='"'+allcp+path+"version/"+name+"/"+version+".jar"+'"',
            auth_player_name=select_user["name"],
            natives_directory='"'+settings.DATA_NATIVES_DIR+("natives-"+settings.PC_OS+"-"+settings.ARCH)+'/"',
            auth_access_token=select_user["uuid"],
            clientid=select_user["clientid"]
    )

    return all_cmd


